<?php

namespace app\api\controller;

use app\common\model\AccountModel;
use app\common\model\AccountRecordModel;
use app\common\model\MealSpeciModel;
use app\common\model\OrderLogModel;
use app\common\service\HttpService;
use app\common\service\WxPayService;
use lib\phpqrcode\QRcode;
use think\App;
use app\common\model\OrderModel;
use app\common\model\MealModel;
use think\Db;
use Wechat;


/**  YSF
 *   订单管理 API
 *   Date: 2018/12/12
 * Class Order
 * @package app\api\controller
 */
class Order extends Base
{
    protected $orderModel;
    protected $orderLogModel;
    protected $mealModel;
    protected $mealSpeciModel;
    protected $ali_config;
    protected $accountModel;
    protected $accountRecordModel;


    // 初始化构造方法
    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->orderModel = new OrderModel();
        $this->orderLogModel = new OrderLogModel();
        $this->mealModel = new MealModel();
        $this->mealSpeciModel = new MealSpeciModel();
        $this->ali_config = config('api.alipay');
        $this->accountModel = new AccountModel();//账户模型
        $this->accountRecordModel = new AccountRecordModel();  // 账户记录表模型
    }

    // 获取订单列表
    public function getOrderAll()
    {
        // 接收参数
        $page = $this->parm['page'] ?? 1;
        $pageSize = $this->parm['pageSize'] ?? 10;
        $o_sn = $this->parm['o_sn'] ?? '';
        $a_sn = $this->parm['a_sn'] ?? '';

        $where = [];
        // 订单类型
        if (!empty($this->parm['order_type'])) {
            $where[] = ['order_type', '=', $this->parm['order_type']];
        }
        // 用户ID
        if (!empty($this->parm['company_id'])) {
            $where[] = ['company_id', '=', $this->parm['company_id']];
        }
        // 订单编号
        if (!empty($this->parm['orderNumber'])) {
            $where[] = ['order_sn', '=', $this->parm['orderNumber']];
        }
        // 支付类型
        if (!empty($this->parm['pay_type'])) {
            $where[] = ['pay_way', '=', $this->parm['pay_type']];
        }
        // 支付状态
        if (!empty($this->parm['pay_status'])) {
            $where[] = ['pay_status', '=', $this->parm['pay_status']];
        }
        // 套餐类型
        if (!empty($this->parm['meal_type'])) {
            $where[] = ['meal_type', '=', $this->parm['meal_type']];
        }
        // 判断用户有没有输开始日期 // 判断用户有没有输结束日期
        if (!empty($this->parm['startTime']) && !empty($this->parm['endTime'])) {
            $where[] = ['pay_time', 'BETWEEN', [strtotime($this->parm['startTime']), strtotime($this->parm['endTime']) + (60 * 60 * 24 - 1)]];
        } else if (!empty($this->parm['startTime'])) {
            $where[] = ['pay_time', '>=', strtotime($this->parm['startTime'])];
        } else if (!empty($this->parm['endTime'])) {
            $where[] = ['pay_time', '<=', strtotime($this->parm['endTime']) + (60 * 60 * 24 - 1)];
        }

        $account_info = $this->accountModel->getCompanyInfo($this->parm['company_id'], $o_sn, $a_sn);
        if (!empty($account_info) && !empty($account_info['account_id'])) {
            $where[] = ['account_id', '=', $account_info['account_id']];
        } else {
            returnJson(0, '暂无账户信息');
        }


        $field = 'order_id,order_sn,order_type,meal_type,scale_price,order_has_pay_money,num,pay_way,pay_time,pay_status,send_money';
        $order = 'create_time DESC';

        // 列表查询
        $data = $this->orderModel->getAll($where, $field, $page, $pageSize, [], $order);
        // 数量查询
        $count = $this->orderModel->getCount($where);
        // 计算总页数
        $page_sum = ceil($count / $pageSize);
        $info = [
            'page_current' => $page,
            'limit' => $pageSize,
            'page_sum' => $page_sum,
        ];
        if ($data) {
            foreach ($data as $k => &$v) {
                $v['scale_price'] = json_decode($v['scale_price']);
                if ($v['order_type'] == 2) {
                    $v['meal_type_name'] = '账户充值';
                } else {
                    $v['meal_type_name'] = empty($v['meal_type']) ? '' : config('api.meal_type')[$v['meal_type']];
                }
                $v['order_has_pay_money'] = '￥' . formatMoney($v['order_has_pay_money']);
                $v['send_money'] = '￥' . formatMoney($v['send_money']);
                $v['pay_way_name'] = empty($v['pay_way']) ? '' : config('api.pay_way')[$v['pay_way']];
                $v['pay_time'] = strlen($v['pay_time']) > 5 ? dateTime($v['pay_time']) : '';
                //$v['pay_status_name'] = config('api.pay_status')[$v['pay_status']];
                if ($v['pay_way'] == 3 && $v['pay_status'] == 1) {
                    $v['pay_status_name'] = '待线下支付';
                } else {
                    $v['pay_status_name'] = config('api.pay_status')[$v['pay_status']];
                }
                $v['order_type_name'] = empty($v['order_type']) ? '' : config('api.order_type')[$v['order_type']];
            }
            returnJson(1, '获取成功', $data, $count, $info);
        }
        returnJson(0, '暂无订单');

    }

    // 获取订单详情
    public function getOrderDetail()
    {
        // 接收参数 -- 判断参数
        if (empty($this->parm['order_id'])) {
            returnJson(0, '缺少参数');
        }
        $order_id = $this->parm['order_id'] ?? '';
        $field = 'order_id,order_sn,order_type,order_total_money,order_has_pay_money,pay_way,order_status,create_time,
                  pay_time,remarks,bank,account';
        $data = $this->orderModel->getOne(['order_id' => $order_id], $field);
        if ($data) {
            $data['order_has_pay_money'] = '￥' . formatMoney($data['order_has_pay_money']);
            $data['order_total_money'] = '￥' . formatMoney($data['order_total_money']);
            $data['order_type_name'] = config('api.order_type')[$data['order_type']];
            $data['pay_way_name'] = config('api.pay_way')[$data['pay_way']];
            $data['order_status_name'] = config('api.order_status')[$data['order_status']];
            $data['create_time'] = strlen($data['create_time']) > 5 ? dateTime($data['create_time']) : '';
            $data['pay_time'] = strlen($data['pay_time']) > 5 ? dateTime($data['pay_time']) : '';
            returnJson(1, '获取成功', $data);
        }
        returnJson(0, '查询订单失败');

    }

    // 支付完成接口
    public function getOrderOne()
    {
        // 接收参数 -- 判断参数
        if (empty($this->parm['order_id'])) {
            returnJson(0, '缺少参数');
        }
        $order_id = $this->parm['order_id'] ?? '';
        $where['order_id'] = $order_id;
        $field = 'order_id,order_sn,order_type,order_status,order_has_pay_money,send_money,pay_way,pay_status';
        $data = $this->orderModel->getOne($where, $field);
        if ($data) {
            $data['pay_money'] = formatMoney($data['order_has_pay_money']);
            returnJson(1, '获取成功', $data);
        }
        returnJson(0, '查询订单失败');

    }

    // 获取选中套餐
    public function buyOrder()
    {
        // 接收参数
        $meal_id = $this->parm['meal_id'] ?? '';
        $speci_id = $this->parm['speci_id'] ?? '';
        if (empty($meal_id) || empty($speci_id)) {
            returnJson(-1001, '缺少参数');
        }
        $where['meal_id'] = $meal_id;
        $field = 'meal_id,name,image,type';
        // 1-- 套餐信息
        $data = $this->mealModel->getOne($where, $field);
        if ($data) {
            $data['image_url'] = config('api.qi_niu_url') . $data['image'];
            $data['type_name'] = config('api.meal_type')[$data['type']];
            $where['id'] = $speci_id;
            $field = 'id,name,sPrice';
            // 2-- 规格信息
            $data['speci'] = $this->mealSpeciModel->getOne($where, $field);
            unset($where);
            if ($data['speci']) {
                $data['speci']['sPrice'] = formatMoney($data['speci']['sPrice']);
            }
            returnJson(1, '成功', $data);
        }
        returnJson(0, '失败', $data);
    }

    /**
     *    生成订单
     */
    public function subOrder()
    {
        // 接收参数
        $meal_id = $this->parm['meal_id'] ?? '';        // 套餐ID
        $speci_id = $this->parm['speci_id'] ?? '';      // 规格ID
        $pay_way = $this->parm['pay_way'] ?? '';        // 支付方式
        $order_type = $this->parm['order_type'] ?? '';  // 订单类型
        $payAccountInfo = $this->parm['payAccountInfo'] ?? config('api.payAccountInfo');  // 对公信息
        $company_id = $this->parm['company_id'] ?? '';          // 入住商ID
        $meal_num = $this->parm['meal_num'] ?? 1;  // 数量
        $payMoney = $this->parm['payMoney'] ?? '';    // 充值金额
        $sendMoney = $this->parm['sendMoney'] ?? '';  // 赠送金额
        $o_sn = $this->parm['o_sn'] ?? '';  // 运营中心编号
        $a_sn = $this->parm['a_sn'] ?? '';  // 城市合伙人编号

        // 订单总金额
        $order_total_money = 0;
        $send_money = 0;//赠送金额
        // 购买套餐
        if ($order_type == 1) {
            if (empty($meal_id) || empty($speci_id) || empty($pay_way) || empty($order_type) || empty($company_id)) {
                returnJson(0, '缺少参数');
            }

            // 1-- 获取套餐数据----------------------------------------------------------------------
            $where['meal_id'] = $meal_id;
            $field = 'meal_id,name,image,type';
            $data = $this->mealModel->getOne($where, $field); // 套餐信息
            if (empty($data)) {
                returnJson(-1000, '套餐不存在');
            }
            $where['id'] = $speci_id;
            $field = 'id,name,sPrice,sales,stock';
            $data['speci'] = $this->mealSpeciModel->getOne($where, $field); // 规格信息
            unset($where);
            // 判断是否有库存
            if ($data['speci']['sales'] + $meal_num > $data['speci']['stock']) {
                returnJson(0, '库存不足');
            }

            $order_data['meal_id'] = $meal_id;           // 套餐ID
            $order_data['meal_name'] = $data['name'];    // 套餐名称
            $order_data['meal_type'] = $data['type'];    // 套餐类型
            $order_data['speci_id'] = $speci_id;         // 套餐ID
            $order_data['scale_price'] = json_encode($data['speci']);      // 套餐规格
            $order_data['num'] = 1;                 // 套餐数量
            // 订单总金额
            $order_total_money = $data['speci']['sPrice'];
        } elseif ($order_type == 2) {// 账户充值
            if (empty($payMoney) || empty($pay_way)) {
                returnJson(0, '缺少参数');
            }

            if (!is_numeric($payMoney)) {
                returnJson(0, '请输入正确的金额');
            }

            // 订单总金额
            $order_total_money = formatMoney($payMoney, 1);          // 充值金额
            $order_data['send_money'] = formatMoney($sendMoney, 1);  // 赠送金额
            $order_data['meal_name'] = '账户充值';    // 名称
            $send_money = $order_data['send_money'];
        }

        // 2-- 生成订单数据-----------------------------------------------------------------------
        // 对公支付
        if ($pay_way == 3) {
            $order_data['bank'] = $payAccountInfo['bank'];
            $order_data['account'] = $payAccountInfo['account'];
            $order_data['unionPay'] = $payAccountInfo['unionPay'];
            $order_data['bank_address'] = $payAccountInfo['bank_address'];
        }
        // 数据组装
        $order_data['company_id'] = $company_id;      // 用户ID|入住商ID
        $order_data['order_sn'] = order_sn();         // 订单编号
        $order_data['order_type'] = $order_type;      // 订单类型
        $order_data['order_status'] = 1;              // 订单状态,1待支付
        $order_data['order_total_money'] = $order_total_money;           // 订单总金额，单位分
        $order_data['order_actual_total_money'] = $order_total_money;    // 订单需要支付总金额，单位分
        $order_data['order_has_pay_money'] = $order_total_money;   // 实际支付金额，单位分
        $order_data['pay_way'] = $pay_way;
        $order_data['pay_status'] = 1;
        if ($pay_way == 3) {
            $order_data['pay_status'] = 2;
            $order_data['order_status'] = 2;
        }
        $order_data['create_time'] = time();

        // 3-- 开始下单---------------------------------------------------------------------------
        //查询账户信息
        $company_info = $this->accountModel->getCompanyInfo($company_id, $o_sn, $a_sn);
        $role = 1;
        $account_sn = $company_info['company_no'];//编号
        if (!empty($o_sn)) {
            $role = 2;
            $account_sn = $o_sn;
        }
        if (!empty($a_sn)) {
            $role = 3;
            $account_sn = $a_sn;
        }
        // 开启事务
        Db::startTrans();
        try {
            $account_id = !empty($company_info['account_id']) ? $company_info['account_id'] : '';
            //没有账户此时新增账户
            if (empty($company_info['account_id'])) {
                $add_data = [
                    'app_sn' => $company_info['app_sn'],
                    'company_no' => $company_info['company_no'] ?? '',
                    'account_role' => $role,
                    'account_sn' => $account_sn,
                    'total_money' => 0,
                    'current_money' => 0,
                    'create_time' => time(),
                ];
                $account_id = $this->accountModel->add($add_data);
                $edit_account=[
                    'total_money'=>$order_total_money+$send_money,
                    'current_money'=>$order_total_money+$send_money,

                ];

            }else{
                $edit_account=[
                    'total_money'=>$company_info['total_money']+$order_total_money+$send_money,
                    'current_money'=>$company_info['total_money']+$order_total_money+$send_money,

                ];
            }
            if ($pay_way == 3 && $order_type == 2) {//对公转账和充值套餐时直接充钱进账户
                $this->accountModel->edit(['id'=>$account_id],$edit_account);
            }
            // 3.1-- 添加订单
            $order_data['account_id'] = $account_id; // 账户id
            $order_id = $this->orderModel->add($order_data);

            // 3.2-- 添加订单日志
            $order_log['order_id'] = $order_id;
            $order_log['operation'] = '下单';
            $order_log['operate_time'] = time();
            $order_log['remark'] = '';
            $this->orderLogModel->add($order_log);

            //对公转账或者支付金额为0时==待处理


            // 事务提交
            Db::commit();
        } catch (\Exception $e) {
            // 事务回滚
            Db::rollback();
            returnJson(0, '下单失败' . $e->getMessage());
        }

        $json['order_id'] = $order_id;
        $json['order_sn'] = $order_data['order_sn'];
        returnJson(1, '下单成功', $json);
    }

    /**
     *   微信支付 模式二 统一下单
     *   生成二维码 支付url有效期为2小时
     */
    public function getQrcode()
    {
        // 接收参数-- 判断参数
        if (empty($this->parm['order_id'])) {
            returnJson(0, '缺少参数');
        }
        $order_id = $this->parm['order_id'] ?? '';
        // 查询订单信息
        $where['order_id'] = $order_id;
        $order_data = $this->orderModel->getOne($where);
        if (!$order_data) {
            returnJson(-1000, '下单失败');
        }

        // 获取配置文件
        $wx_config = $this->api_config['wechat'];
        $order_info['order_sn'] = $order_data['order_sn'];
        $order_info['order_id'] = $order_data['meal_id'] ?? $order_data['order_id'];
        $order_info['money'] = formatMoney($order_data['order_actual_total_money'], 2);
        if (config('api.develop_mode')) {
            $order_info['money'] = 0.01;
        }
        $notify_url = HttpService::getDomain().'/'. $this->api_config['notify_url']; //微信回调地址
        $code = WxPayService::nativePay($wx_config, $order_info, $notify_url, '', 1);
        if ($code['return_code'] == 'SUCCESS' && $code['result_code'] == 'SUCCESS') {
            $url2 = $code["code_url"];
            $code_url = $this->getCode($url2, $order_data['order_sn'], 'wxqrcode');
        } else {
            returnJson(0, $code['return_msg'] == 'OK' ? '该订单已经支付成功' : $code['return_msg']);
        }

        if ($code_url) {
            $json['order_id'] = $order_id;
            $json['name'] = $order_data['meal_name'];
            $json['order_sn'] = $order_data['order_sn'];
            $json['pay_money'] = formatMoney($order_data['order_has_pay_money']);
            $json['code_url'] = HttpService::getDomain().'/'. $code_url;
            returnJson(1, '下单成功', $json);
        }
        returnJson(0, '下单失败');
    }

    /**
     *    微信支付状态--查询
     */
    public function payStatus()
    {
        // 接收参数-- 判断参数
        if (empty($this->parm['order_sn'])) {
            returnJson(0, '缺少参数');
        }
        $order_sn = $this->parm['order_sn'] ?? '';
        $wx_config = $this->api_config['wechat']; // 获取配置文件
        $result = WxPayService::queryPayStatus($wx_config, $order_sn);
        returnJson($result['code'], $result['msg']);
    }

    /**
     *   生成二维码
     * @param $url        链接url
     * @param $order_sn   订单编号
     * @param $dir        目录
     * @param bool $logo logo
     * @return string
     */
    public function getCode($url, $order_sn, $dir, $logo = false)
    {
        require_once "../extend/lib/phpqrcode/phpqrcode.php"; // 引入url生成二维码

        $errorCorrectionLevel = 'L';    //容错级别
        $matrixPointSize = 5;           //生成图片大小
        //生成二维码图片
        $date = date('Ymd') . '/';
        $path = './uploads/' . $dir . '/';
        file_exists($path) || mkdir($path, 0777);
        $file = $order_sn . '.png';
        $filename = $path . $file;
        QRcode::png($url, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
        $logo = $logo; //准备好的logo图片
        $QR = $filename; //已经生成的原始二维码图
        $QR = imagecreatefromstring(file_get_contents($QR));
        if ($logo !== false) {
            $logo = imagecreatefromstring(file_get_contents($logo));
            $QR_width = imagesx($QR); //二维码图片宽度
            $QR_height = imagesy($QR); //二维码图片高度
            $logo_width = imagesx($logo); //logo图片宽度
            $logo_height = imagesy($logo); //logo图片高度
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width / $logo_qr_width;
            $logo_qr_height = $logo_height / $scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            //重新组合图片并调整大小
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
        }

        //输出图片
        imagepng($QR, $filename);
        $filename = trim($filename, '.');
        return $filename;
    }


}